package com.Xht.www.servlet;

import com.Xht.www.dao.AdminInfoDAO;
import com.Xht.www.po.AdminInfoPO;
import com.Xht.www.util.ValidationUtil;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

//后端接收管理员登录请求

@WebServlet("/admin/login")
public class AdminLoginServlet extends HttpServlet {
    private AdminInfoDAO adminInfoDAO = new AdminInfoDAO();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应格式为 JSON
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        // 获取请求参数
        String adminName = request.getParameter("adminName");
        String password = request.getParameter("password");

        // 构建参数 Map 用于工具类校验
        Map<String, String> params = new HashMap<>();
        params.put("adminName", adminName);
        params.put("password", password);

        // 调用工具类进行输入校验
        ValidationUtil.ValidationResult result = ValidationUtil.validateInput("admin-login", params);

        if (!result.isSuccess()) {
            out.write("{\"success\": false, \"message\": \"" + result.getMessage() + "\"}");
            out.close();
            return;
        }

        // 参数合法，继续执行登录逻辑
        AdminInfoPO admin = adminInfoDAO.getAdminInfoByName(adminName);

        if (admin != null && admin.getAdminPassword().equals(password)) {
            out.write("{\"success\": true, \"message\": \"管理员登录成功\"}");
        } else {
            out.write("{\"success\": false, \"message\": \"管理员名称或密码错误\"}");
        }

        out.close();
    }
}
